<template>
  <div class="app-container">
    <div class="operation-container">
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="用户名">
            <el-input v-model="listQuery.username" placeholder="请输入用户名" class="filter-item" />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="listQuery.phone" placeholder="请输入手机号码" class="filter-item" />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="listQuery.name" placeholder="请输入昵称" class="filter-item" />
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" round icon="el-icon-search" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button class="filter-item" type="primary" round icon="el-icon-success" @click="toggleSelection">
        批量选择/取消
      </el-button>
      <el-button class="filter-item" type="primary" round icon="el-icon-edit" @click="handleCreate">
        新增用户
      </el-button>
    </div>
    <div class="operation-container">
      <el-table
        ref="userTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-dblclick="handleRowDblclick"
      >
        <el-table-column
          type="selection"
          align="center"
          width="45"
        />
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column
          label="昵称"
          prop="name"
        />
        <el-table-column
          label="用户名"
          prop="username"
        />
        <el-table-column
          label="邮箱"
          prop="email"
        />
        <el-table-column
          label="手机号码"
          prop="phone"
        />
        <el-table-column label="头像" prop="avatar">
          <template slot-scope="{row}">
            <el-avatar shape="square" :src="row.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="sex">
          <template slot-scope="{row}">
            <template v-for="(item,index) in dict['sys_user_sex']">
              <el-tag v-if="item.value === row.sex" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col" align="center" width="100">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.status"
              active-value="Y"
              inactive-value="N"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleSwitch(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template slot-scope="{row}">
            <i class="el-icon-time margin-right-5" />
            <span>{{ row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleUpdate(row)">
              <i class="el-icon-edit" />修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNumber" :limit.sync="listQuery.pageSize" append-to-body @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" width="600px" append-to-body :visible.sync="dialog">
      <el-form
        ref="dataForm"
        label-width="100px"
        :model="user"
        :rules="rules"
      >
        <el-form-item v-if="dialogStatus !== 'update'" prop="username" label="用户名">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item v-if="dialogStatus !== 'update'" prop="password" label="用户密码">
          <el-input v-model="user.password" type="password" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="name">
              <el-input v-model="user.name" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="user.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="user.sex" placeholder="请选择">
                <template v-for="(item,index) in dict['sys_user_sex']">
                  <el-option :key="index" :value="item.value" :label="item.label" />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="user.roleIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in role"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="user.status"
                active-value="Y"
                inactive-value="N"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="user.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>

import { create, userFetchList, update, updateStatus } from '@/api/user'
import { userRole } from '@/api/role'
import Pagination from '@/components/Pagination/index'
import { mapGetters } from 'vuex'
import { MessageBox } from 'element-ui'
import { list } from '@/api/role'

export default {
  name: 'UserTable',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      listLoading: true,
      list: null,
      total: 0,
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        username: undefined,
        phone: undefined,
        name: undefined
      },
      user: {
        id: undefined,
        name: undefined,
        username: undefined,
        password: undefined,
        email: undefined,
        phone: undefined,
        status: 'Y',
        roleIds: [],
        remark: undefined
      },
      multipleSelection: [],
      dialog: false,
      dialogStatus: '',
      textMap: {
        update: '修改用户',
        create: '添加用户'
      },
      role: [],
      rules: {
        username: [
          { required: true, trigger: 'blur', message: '用户名不能为空' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能少于6位' }
        ],
        name: [
          { required: true, trigger: 'blur', message: '昵称不能为空' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'dict'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      userFetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.2 * 1000)
      })
    },
    indexMethod(index) {
      return index + 1
    },
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.user.id) {
            update(this.user.id, this.user).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '修改完成',
                message: '修改账号:（' + this.user.username + '） 信息成功！',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            create(this.user).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '新增完成',
                message: '新增账号:（' + this.user.username + '）信息成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    // 创建事件
    handleCreate() {
      this.resetFields()
      list().then(response => {
        this.role = response.data
      })
      this.dialogStatus = 'create'
    },
    // 修改事件
    handleUpdate(row) {
      this.resetFields()
      this.user = Object.assign({}, row)
      userRole(row.id).then(response => {
        this.role = response.data.list
        this.user.roleIds = response.data.roleIds
      })
      this.dialogStatus = 'update'
    },
    // 查询事件
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        pageNumber: 1,
        pageSize: 10,
        username: undefined,
        phone: undefined,
        name: undefined
      }
    },
    // 处理选择更改
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量选择
    toggleSelection() {
      if (this.list) {
        if (this.list.length === this.multipleSelection.length) {
          this.$refs.userTable.clearSelection()
        } else {
          this.$refs.userTable.toggleAllSelection()
        }
      }
    },
    // 用户状态转换事件
    handleSwitch(row) {
      const text = row.status === 'N' ? '启用' : '停用'
      MessageBox.confirm('是否变更状态为' + text, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStatus(row.id).catch(() => {
          row.status = row.enabled === 'N' ? 'Y' : 'N'
        })
      }).catch(function() {
        row.status = row.enabled === 'N' ? 'N' : 'Y'
      })
    },
    //  当某一行被双击时会触发该事件
    handleRowDblclick(row) {
      this.$refs.userTable.toggleRowSelection(row)
    },
    resetFields() {
      this.user = {
        id: undefined,
        name: undefined,
        username: undefined,
        password: undefined,
        email: undefined,
        phone: undefined,
        status: 'Y',
        roleIds: [],
        remark: undefined
      }
      if (this.$refs['dataForm'] !== undefined) {
        this.$refs['dataForm'].resetFields()
      }
      this.dialog = true
    }
  }
}
</script>
